/*angular.module('logincat', []).
  config(['$routeProvider', function($routeProvider) {
  $routeProvider.
      when('/', {templateUrl: '/static/views/login.html',   controller: LoginCtrl}).
      otherwise({redirectTo: '/'});}
      $httpProvider.defaults.headers.post['X-CSRFToken'] = $('input[name=csrfmiddlewaretoken]').val();
]);*/

var logincat = angular.module('logincat', ['ui.bootstrap.modal', 'ui.calendar', 'ui.bootstrap.rating']).
	config(function($routeProvider, $httpProvider) {
		$routeProvider.when('/', {templateUrl: '/static/views/home.html', controller: HomeCtrl});
		//$routeProvider.when('/', {templateUrl: '/static/views/login.html',   controller: LoginCtrl});
		$routeProvider.otherwise({redirectTo: '/'});
		/*$http({
			method: 'POST',
			url: '/',
			data: {'X-CSRFToken', 'CSRFToken'},
			headers: {'Content-Type': 'application/x-www-form-urlencoded'}
		});*/
		//$httpProvider.defaults.headers.common['CSRF-TOKEN'] = "CSRFToken";
	});

function LoginCtrl($scope, $routeParams, $http) {
};

function HomeCtrl($scope, $routeParams, $http) {

};

function loginCtrl($scope, $http) {
	$scope.master = {};

	$scope.update = function(user) {
		$scope.master = angular.copy(user);
	};

	$scope.reset = function() {
		$scope.user = angular.copy($scope.master);
	};

	$scope.loginSubmit = function loginSubmit() {
		//$httpProvider.defaults.headers.common['X-CSRF-Token'] = $('meta[name=csrf-token]').attr('content');
		//$http.defaults.headers.post['X-XSRF-TOKEN'] = 'CSRFToken';

		$http.post("/login/login", JSON.stringify($scope.master))
		.success(function(data) {
			alert(data.username);
			$scope.master.username = "success";
			$location("http://baidu.com");
		}).error(function(data) {
			alert("error");
			$scope.master.username = "error";
		});

	}

	$scope.reset();
}

function ModalDemoCtrl ($scope, $http) {
	$scope.master = {};
	/* event source that pulls from google.com */
	$scope.eventSource = {};
	$scope.scheduleList = [];
	$scope.eventList = [];

	function init() {
		getEventList();
		getScheduleList();
	}

	$scope.open = function () {
		$scope.addModal = true;
	};

	$scope.close = function () {
		$scope.addModal = false;
		$scope.updateModal = false;
	};

	function getEventList() {
		$http.post("/index/getEventList", {}).
		success(function (data) {
			//alert(data.eventList[0].id);
			$scope.eventList = [];
			var i;
			for (i = 0; i < data.eventList.length; ++i) {
				$scope.eventList.push({
					id : data.eventList[i].id,
					title : data.eventList[i].title,
					start_time : data.eventList[i].start_time,
					end_time : data.eventList[i].end_time,
					location : data.eventList[i].location,
					time_cost : data.eventList[i].time_cost,
					importance : data.eventList[i].importance,
					sensitive_to_weather : data.eventList[i].sensitive_to_weather
				})
			}
		}).
		error(function (data) {
			alert("Fail to load event list!");
		})
	}

	function getScheduleList() {
		$http.post("/index/getScheduleList", {}).
		success(function (data) {
			//alert(data.scheduleList.length)
			$scope.scheduleList = [];
			var i;
			for (i = 0; i < data.scheduleList.length; ++i) {
				alert(new Date(data.scheduleList[i].end_time))
				$scope.scheduleList.push({
					//id : data.scheduleList[i].id,
					title : data.scheduleList[i].title,
					start : new Date(data.scheduleList[i].start_time),
					end : new Date(data.scheduleList[i].end),
					fullDay : false,
					className: ['openSesame']
				})
			}
			/* event sources array*/
			$scope.eventSources = [$scope.scheduleList, $scope.eventSource, $scope.eventsF];
		}).
		error(function (data) {
			alert("Fail to load schedule list!");
		})
	}

	$scope.addEvent = function (new_event) {
		//alert(importance);
		//alert($scope.importance);
		$scope.clear();
		$scope.master = angular.copy(new_event);
		$scope.master.start_time = $('input[name=start_time]').val();
		$scope.master.end_time = $('input[name=end_time]').val();
		$scope.master.importance = $scope.importance;
		$scope.master.sensitive_to_weather = $scope.sensitive_to_weather;
		//alert($scope.sensitive_to_weather);
		$http.post("/index/addevent", {
			start_time : $('input[name=start_time]').val(),
			end_time : $('input[name=end_time]').val(),
			title : $scope.master.title,
			importance : $scope.importance,
			sensitive_to_weather : $scope.sensitive_to_weather,
			location : $scope.location,
			time_cost : $scope.time_cost
		}).success(function (data, status) {
			$scope.master.id = data.id;
			$scope.eventList.push({
				id : data.id,
				title : new_event.title,
				start_time : $scope.master.start_time,
				end_time : $scope.master.end_time,
				location : new_event.location,
				time_cost : new_event.time_cost,
				importance : $scope.importance,
				sensitive_to_weather : $scope.sensitive_to_weather});
			//alert($scope.eventList);
//			getScheduleList();
			$scope.clear();
		}).error(function (data, status) {
			alert("error");
			$scope.clear();
		})
		$scope.close();
	}

	$scope.updateEvent = function (event) {
		//$scope.master = angular.copy(event);
/*		$scope.master.start_time = "";
		$scope.master.end_time = "";
		$scope.master.start_time = $('input[name=start_time]').val();
		$scope.master.end_time = $('input[name=end_time]').val();
		$scope.master.id = event.id;
		$scope.master.importance = event.importance;
		$scope.master.sensitive_to_weather = event.sensitive_to_weather;*/
		//alert($scope.master.id)
		alert($scope.master.title);
		$http.post("/index/updateEvent", {
			id : $scope.master.id,
			start_time : $('input[name=start_time]').val(),
			end_time : $('input[name=end_time]').val(),
			title : $scope.master.title,
			importance : $scope.importance,
			sensitive_to_weather : $scope.sensitive_to_weather,
			location : $scope.location,
			time_cost : $scope.time_cost
		}).
		success(function (data) {
			$scope.close();
		}).
		error(function (data) {
			alert("Fail to update event!");
		});
		$scope.updateModal = false;
		$scope.clear();
	}

	$scope.clear = function () {
		$scope.master.title = "";
		$scope.master.start_time = "";
		$scope.master.end_time = "";
		$scope.master.location = "";
		$scope.master.time_cost = "";
	}

    $scope.remove = function(index) {
    	//alert($scope.eventList[index].id);
    	$http.post("/index/deleteEvent", {id : $scope.eventList[index].id}).
    	success(function (data, status) {
    		$scope.eventList.splice(index, 1);
    		getScheduleList();
    	}).
    	error(function (data, status) {

    	});
    };

    $scope.fillModal = function() {
    	//alert("fillModal");
    	$('#datetimepicker_start_time').datetimepicker({
    		language: 'en',
    		pick12HourFormat: false,
    		pickSeconds: false
    	});
    	$('#datetimepicker_end_time').datetimepicker({
    		language: 'en',
    		pick12HourFormat: false,
    		pickSeconds: false
    	});
    	if ($('#title').val() == "") {
    		$('#title').val($scope.master.title);
    	}
    	if ($('input[name=start_time]').val() == "") {
    		$('input[name=start_time]').val($scope.master.start_time);
    	}
    	if ($('input[name=end_time]').val() == "") {
    		$('input[name=end_time]').val($scope.master.end_time);
    	}
    	if ($('#time_cost').val() == "") {
    		$('#time_cost').val($scope.master.time_cost);
    	}
    	if ($('#location').val() == "") {
    		$('#location').val($scope.master.location);
    	}
    }

    $scope.edit = function(index) {
    	//alert($scope.master.title);
    	//alert($scope.eventList[index].title);
    	//alert($scope.eventList[index].start_time);
    	$scope.updateModal = true;
    	$scope.master.title = $scope.eventList[index].title;
    	$scope.master.start_time = $scope.eventList[index].start_time;
    	$scope.master.end_time = $scope.eventList[index].end_time;
    	$scope.master.id = $scope.eventList[index].id;
    	$scope.master.time_cost = $scope.eventList[index].time_cost;
    	$scope.master.location = $scope.eventList[index].location;
    	$scope.importance = $scope.eventList[index].importance;
    	$scope.sensitive_to_weather = $scope.eventList[index].sensitive_to_weather;
    }

	$scope.opts = {
		backdropFade : true,
		dialogFade : true
	};

	/* event source that calls a function on every view switch */
    /* event source that calls a function on every view switch */
    $scope.eventsF = function (start, end, callback) {
      var s = new Date(start).getTime() / 1000;
      var e = new Date(end).getTime() / 1000;
      var m = new Date(start).getMonth();
      var events = [{
      	title : 'Feed Me ' + m,
      	start : s + (50000),
      	end : s + (100000),
      	allDay : false,
      	className : ['customFeed']}];
      callback(events);
    };
    /* alert on eventClick */
    $scope.alertEventOnClick = function( date, allDay, jsEvent, view ){
        $scope.$apply(function(){
        	//alert(date);
        	$scope.myCalendar.fullCalendar('gotoDate', date)
        	$scope.myCalendar.fullCalendar('changeView', "agendaDay");
        	$scope.alertMessage = ('Day Clicked ' + date);
        });
    };
    /* alert on Drop */
     $scope.alertOnDrop = function(event, dayDelta, minuteDelta, allDay, revertFunc, jsEvent, ui, view){
        $scope.$apply(function(){
          $scope.alertMessage = ('Event Droped to make dayDelta ' + dayDelta);
        });
    };
    /* alert on Resize */
    $scope.alertOnResize = function(event, dayDelta, minuteDelta, revertFunc, jsEvent, ui, view ){
        $scope.$apply(function(){
          $scope.alertMessage = ('Event Resized to make dayDelta ' + minuteDelta);
        });
    };
    /* add and removes an event source of choice */
    $scope.addRemoveEventSource = function(sources,source) {
      var canAdd = 0;
      angular.forEach(sources,function(value, key){
        if(sources[key] === source){
          sources.splice(key,1);
          canAdd = 1;
        }
      });
      if(canAdd === 0){
        sources.push(source);
      }
    };

    $scope.gotoClickedDate = function(event, eventElement) {
    	//alert(new Date(event.start.getFullYear(), event.start.getMonth(), event.start.getDate()));

    	$scope.myCalendar.fullCalendar('gotoDate', new Date(event.start.getFullYear(), event.start.getMonth(), event.start.getDate()));
    	$scope.myCalendar.fullCalendar('changeView', "agendaDay");
    }
	/* Change View */
	$scope.changeView = function(view) {
		//alert(view)
		$scope.myCalendar.fullCalendar('changeView', view);
	};
	/* config object */
	$scope.uiConfig = {
		calendar:{
			height: 450,
			editable: true,
			header:{
				left : '',
				center: 'title',
				right: 'today prev,next'
			},
			dayClick: $scope.alertEventOnClick,
			eventDrop: $scope.alertOnDrop,
			eventResize: $scope.alertOnResize,
			eventClick : $scope.gotoClickedDate
		}
	};
	//init();

	$http.post("/index/getScheduleList", {}).
	success(function (data) {
		//$scope.scheduleList = [];
		var i;
		for (i = 0; i < data.scheduleList.length; ++i) {
			$scope.scheduleList.push({
					//id : data.scheduleList[i].id,
					title : data.scheduleList[i].title,
					start : new Date(data.scheduleList[i].start_time),
					end : new Date(data.scheduleList[i].end_time),
					location : data.scheduleList[i].location
				})
		}
		//alert($scope.scheduleList.length)
		/* event sources array*/
	}).
	error(function (data) {
		alert("Fail to load schedule list!");
	})
	getEventList();
	$scope.eventSources = [$scope.scheduleList, $scope.eventSource, $scope.eventsF];

	$scope.sensitive_to_weather = 0;
	$scope.importance = 0;
}
